package ${packageName};

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.PathBuilder;
import com.wuyan.web.base.aop.ApiLogAnnotation;
import com.wuyan.web.base.helper.rep.RepBody;
import com.wuyan.web.base.helper.rep.RepHelper;
import com.wuyan.web.base.helper.rep.RepPageData;
import com.wuyan.web.base.helper.rep.RepCodeEnum;
import com.wuyan.web.base.helper.req.CustomQueryHelper;
import com.wuyan.web.base.helper.req.CustomQueryParams;
import com.wuyan.web.base.helper.req.CustomQueryOrderParams;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import ${entity.packageName}.${entity.className};
import ${entity.packageName}.Q${entity.className};
import ${lastRenderResponse.form.packageName}.${lastRenderResponse.form.className};
import ${lastRenderResponse.service.packageName}.${lastRenderResponse.service.className};
import lombok.extern.slf4j.Slf4j;

<#list imports as import>
<#if import!="java.lang.Integer">
import ${import};
</#if>
</#list>

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * controller for ${entity.className} generated by jpa-codegen
 * ${comments}
 * 接口遵循restful规范，其中post用于新增，get用于查询数据，put用于修改，delete用于删除，默认增加分页查询接口
 *
 * @author ${author}
 * @date ${date}
 */

@Slf4j
@RestController
@RequestMapping("${otherParams.url_prefix}/${entity.className?replace("([a-z])([A-Z]+)", "$1-$2", "r")?lower_case}")
public class ${className} implements RepHelper {

    @Autowired
    private ${lastRenderResponse.service.className} ${lastRenderResponse.service.className?uncap_first};

    @PostMapping
    @ApiLogAnnotation(name = "${entity.className}:create")
    public RepBody<${entity.className}> create(@RequestBody @Validated ${lastRenderResponse.form.className} form) throws Exception {
        ${entity.className} ${entity.className?uncap_first} = ${lastRenderResponse.service.className?uncap_first}.create(form);
        return ok(${entity.className?uncap_first});
    }

    @PostMapping("/plist")
    @ApiLogAnnotation(name = "${entity.className}:creates")
    public RepBody<List<${entity.className}>> creates(@RequestBody @Validated List<${lastRenderResponse.form.className}> forms) throws Exception {
        List<${entity.className}> res = ${lastRenderResponse.service.className?uncap_first}.creates(forms);
        return ok(res);
    }

    @DeleteMapping("/{id}")
    @ApiLogAnnotation(name = "${entity.className}:delete")
    public RepBody<Integer> delete(@PathVariable("id") ${entity.id.className}[] id) {
        return ok(${lastRenderResponse.service.className?uncap_first}.delete(id));
    }

    @PutMapping("/{id}")
    @ApiLogAnnotation(name = "${entity.className}:update")
    public RepBody<${entity.className}> update(@RequestBody @Validated ${lastRenderResponse.form.className} form,
                                    @PathVariable("id") ${entity.id.className} id) throws Exception {
        Optional<${entity.className}> ${entity.className?uncap_first} = ${lastRenderResponse.service.className?uncap_first}.update(form, id);
        return ${entity.className?uncap_first}.isPresent() ? ok(${entity.className?uncap_first}.get()) : error(RepCodeEnum.ERR_NO_ID);
    }

    /**
    * 根据ID更新指定字段的值
    *
    * @param id    id
    * @param field 字段名
    * @param value 值
    * @return RepBody<Object>
    */
    @PutMapping("/{id}/{field}/{value}")
    @ApiLogAnnotation(name = "${entity.className}:updateByField")
    public RepBody<Long> updateByField(@PathVariable("id") Integer id,
                                        @PathVariable("field") String field,
                                        @PathVariable("value") String value) throws Exception {
        long update = ${lastRenderResponse.service.className?uncap_first}.updateByField(id, field, value);
        return update > 0 ? ok(update) : error(RepCodeEnum.ERR_UPDATE);
    }

    @GetMapping("/{id}")
    @ApiLogAnnotation(name = "${entity.className}:get")
    public RepBody<${entity.className}> get(@PathVariable("id") ${entity.id.className} id) {
        Optional<${entity.className}> ${entity.className?uncap_first} = ${lastRenderResponse.service.className?uncap_first}.get(id);
        return ${entity.className?uncap_first}.isPresent() ? ok(${entity.className?uncap_first}.get()) : error(RepCodeEnum.ERR_NO_ID);
    }

    /**
    *
    * @param isPage 是否分页
    * @param page 当前页
    * @param limit 条目数
    * @param params 查询参数：数组形式JSON字符串
    * @param ordersParams 排序参数：数组形式JSON字符串
    * @return RepBody<RepPageData<${entity.className}>>
    */
    @SneakyThrows
    @GetMapping
    @ApiLogAnnotation(name = "${entity.className}:page")
    public RepBody<RepPageData<${entity.className}>> page(@RequestParam(value = "isPage", required = false, defaultValue = "true") Boolean isPage,
                                                          @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                                                          @RequestParam(value = "limit", required = false, defaultValue = "15") Integer limit,
                                                          @RequestParam(value = "params", required = false, defaultValue = "[]") String params,
                                                          @RequestParam(value = "orders", required = false, defaultValue = "[]") String ordersParams) {

        ObjectMapper mapper = new ObjectMapper();
        // 查询参数
        List<CustomQueryParams> paramsList = mapper.readValue(params, new TypeReference<List<CustomQueryParams>>() {});
        // 排序参数
        List<CustomQueryOrderParams> orderList = mapper.readValue(ordersParams, new TypeReference<List<CustomQueryOrderParams>>() {});

        Q${entity.className} q = Q${entity.className}.${entity.className?uncap_first};
        PathBuilder<${entity.className}> pathBuilder = new PathBuilder<>(${entity.className}.class, q.getMetadata());

        // 默认排序
        if(null == orderList || orderList.isEmpty()){
            orderList = new ArrayList<>();
            <#if entity.fields?? && (entity.fields?size > 0)>
                <#list entity.fields as f>
                    <#if f.name == "cfgSort">
            CustomQueryOrderParams cfgSortOrder = CustomQueryOrderParams.builder()
                    .filedName("cfgSort")
                    .order(Order.DESC)
                    .build();
            orderList.add(cfgSortOrder);
                        <#continue>
                    </#if>
                    <#if f.name == "createTime">
            CustomQueryOrderParams createTimeOrder = CustomQueryOrderParams.builder()
                    .filedName("createTime")
                    .order(Order.DESC)
                    .build();
            orderList.add(createTimeOrder);
                        <#continue>
                    </#if>
                </#list>
            </#if>
        }

        // 构建查询条件
        CustomQueryHelper<${entity.className}> customQueryHelper = CustomQueryHelper.<${entity.className}>builder()
                    .paramsList(paramsList)
                    .pathBuilder(pathBuilder)
                    .paramsOrders(orderList)
                    .entityClass(${entity.className}.class)
                    .build()
                    .structure();

        List<Predicate> predicates = customQueryHelper.getPredicates();
        List<OrderSpecifier<?>> orders = customQueryHelper.getOrders();

        // TODO 业务逻辑
        // TODO 业务逻辑

        return ok(${lastRenderResponse.service.className?uncap_first}.page(predicates, orders, isPage, page, limit));
    }

}